const router = require("express").Router();
const path = require("path");
const fs = require("fs");
const multer = require("multer");
const { auth } = require("../middleware/auth");

// 子路由
router.use("/auth", require("./auth.routes"));
router.use("/posts", require("./posts.routes"));
router.use("/comments", require("./comments.routes"));
router.use("/tags", require("./tags.routes"));
router.use("/users", require("./users.routes"));

// 简单健康检查
router.get("/health", (req, res) => res.json({ status: "ok" }));

// ====== 图片上传（示例） ======
const uploadDir = path.join(process.cwd(), "uploads");
if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });

// 使用磁盘存储，文件名加时间戳避免覆盖
const storage = multer.diskStorage({
    destination: (_, __, cb) => cb(null, uploadDir),
    filename: (_, file, cb) => {
        const ext = path.extname(file.originalname);
        const base = path.basename(file.originalname, ext);
        cb(null, `${base}-${Date.now()}${ext}`);
    },
});
const upload = multer({
    storage,
    limits: { fileSize: 5 * 1024 * 1024 }, // 5MB
});

// 需要登录
router.post("/upload", auth(true), upload.single("file"), (req, res) => {
    const url = `/uploads/${req.file.filename}`;
    res.status(201).json({ message: "上传成功", url });
});

module.exports = router;
